const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
exports.main = async (event) => {
  const { _id, code } = event;

  const db = cloud.database();

  try {
    const course = await db.collection('course').doc(_id).get();

    if (!course.data) {
      throw new Error('找不到该课程');
    }
    let leaveStudents = course.data.leaveStudents ? course.data.leaveStudents : []
    if (leaveStudents.indexOf(code) !== -1) {
      throw new Error('你已请假');
    }
    leaveStudents.push(code)
    await db.collection('course').doc(_id).update({
      data: {
        leaveStudents: leaveStudents
      },
    });

    return {
      success: true,
      message: '请假成功',
    };
  } catch (error) {
    return {
      success: false,
      message: '请假失败',
      error: error.message,
    };
  }
};
